
#include <iostream>

#include "SDL.h"
#include "ddc_input.h"
#include "ddc_internal.h"
#include "ddc_scancode.h"

char DDC_InputManager::_keyState = 0;
char DDC_InputManager::_mouseButtonState = 0;
const uint8_t *DDC_InputManager::_currentKeyStates = nullptr;

SDL_Event *__currentEvent = NULL;

void DDC_InputManager::__Update() {
    SDL_Event *event = __currentEvent;

    _currentKeyStates = SDL_GetKeyboardState(NULL);

    char _revShift;

    if (event->type == SDL_MOUSEBUTTONDOWN || event->type == SDL_MOUSEBUTTONUP) {
        if (event->button.button == SDL_BUTTON_LEFT)
            _revShift = 3;
        else if (event->button.button == SDL_BUTTON_MIDDLE)
            _revShift = 2;
        else if (event->button.button == SDL_BUTTON_RIGHT)
            _revShift = 1;
    }

    switch (event->type) {

    case SDL_KEYDOWN:
        _keyState = 1;
        break;

    case SDL_KEYUP:
        _keyState = -1;
        break;

    case SDL_MOUSEBUTTONUP:
        _mouseButtonState |= (1 << _revShift);
        break;

    case SDL_MOUSEBUTTONDOWN:
        _mouseButtonState &= ~(1 << _revShift);
        break;

    default:
        _keyState = 0;
    }
}

bool DDC_InputManager::IsMouseDown() {
    return __currentEvent->type == SDL_MOUSEBUTTONDOWN;
}

bool DDC_InputManager::IsMouseUp() {
    return __currentEvent->type == SDL_MOUSEBUTTONUP;
}

bool DDC_InputManager::IsKeyDown() {
    return _keyState == 1;
}

bool DDC_InputManager::IsKeyUp() {
    return _keyState == -1;
}

void DDC_InputManager::GetMouseKeyState(char *key) {
    *key = _mouseButtonState;
}

void DDC_InputManager::GetMousePosition(int *x, int *y) {
    SDL_GetMouseState(x, y);
}

bool DDC_InputManager::GetKeyState(DDC_Scancode::_DDC_ScancodeEnum scancode) {
    if (DDC_InputManager::_currentKeyStates == nullptr) {
        std::cerr << "DDC_Warning: DDC_InputManager::_currentKeyStates == nullptr" << std::endl;
        return false;
    }
    return _currentKeyStates[scancode];
}
